import { PageHeaderWrapper, ProColumns, ProTable } from '@ant-design/pro-components';

import {
  getOnsiteSupportByPage,
  addOnsiteSupport,
  updateOnsiteSupport,
  delOnsiteSupport,
  onsiteSupportExport,
} from '@/services/sales/onsiteSupport';
import { text } from 'express';
import { useAccess, history } from 'umi';
import { useRef, useState } from 'react';
import { Button, Form, Input, message, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

//

const OnsiteSupport: React.FC<{}> = () => {
  const access = useAccess();
  const [rowData, setRowData] = useState({ id: '' });
  const actionRef = useRef<ActionType>();
  const [deleteVisit, setDeleteVisit] = useState(false); // 删除提示框
  const formRef = useRef(null);
  // const [formTitle, setFormTitle] = useState('新建现场支持');
  const [form] = Form.useForm();
  const [filterValue, SetFilterValue] = useState({});
  const ref = useRef(null);

  const operation = access.canAdmin() || access.canChiefEngineer() ? false : true;

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
      align: 'center',
    },
    {
      title: '唯一标识',
      dataIndex: 'onsiteSupportId',
      align: 'center',
      render: (text, record, _, action) => (
        <a
          key="linkkey"
          onClick={() => {
            history.push({
              pathname: `/engineer/onsiteSupportDetail`,
              query: {
                id: record.id,
                status: record.status,
              },
            });
          }}
        >
          {text}
        </a>
      ),
    },
    {
      title: '状态',
      dataIndex: 'supportStatus',
      align: 'center',
      // render: (_, record) => (
      //     <Tag color={record.isFinished ===1 ? 'green' : 'blue'}>
      //       {record.isFinished===1 ? '已完成' : (record.isFinished===0 ?'待处理':'已保存')}
      //     </Tag>
      //   ),
      valueEnum: {
        0: { text: '未完成', status: 'Warning' },
        1: { text: '已完成', status: 'Success' },
        2: { text: '已保存', status: 'Processing' },
      },
    },
    {
      title: '标题',
      dataIndex: 'supportTitle',
      align: 'center',
    },
    {
      title: '支持日期',
      // valueType: 'dateRange',
      dataIndex: 'supportDate',
      search: false,
      align: 'center',
      sorter: true,
    },
    {
      title: '支持日期',
      valueType: 'dateRange',
      dataIndex: 'supportDate',
      hideInTable: true,
      align: 'center',
    },
    {
      title: '客户名称',
      search: false,
      dataIndex: 'customerName',
      align: 'center',
    },
    {
      title: 'BD或销售名称',
      search: false,
      dataIndex: 'bdOrSalesName',
      // hideInTable: true,
      align: 'center',
    },
    {
      title: '区域',
      dataIndex: 'supportArea',
      valueType: 'select',
      align: 'center',
      valueEnum: {
        1: 'RC',
        2: 'RE',
        3: 'RS',
        4: 'RW',
        5: 'RN',
        6: 'RNE',
      },
    },
    {
      title: '行业',
      dataIndex: 'branch',
      valueType: 'select',
      align: 'center',
      valueEnum: {
        1: '电子',
        2: '电池',
        3: '物流',
        4: '汽车',
        5: '太阳能',
        6: '增材制造',
        7: '包装',
        8: '食品饮料',
        9: '金属加工',
        10: '其他',
      },
    },
    {
      title: '设备名称',
      search: false,
      dataIndex: 'machineName',
      align: 'center',
    },
    {
      title: '驱动类型',
      dataIndex: 'driveType',
      align: 'center',
      // valueType: 'select',
      // valueEnum: {
      //     1: 'V90',
      //     2: 'S210',
      //     3: 'G120',
      // },
    },
    {
      title: '支持工程师',
      dataIndex: 'createName',
      align: 'center',
    },
    {
      title: '支持类型',
      dataIndex: 'supportType',
      align: 'center',
      valueType: 'select',
      valueEnum: {
        1: '测试',
        2: '拜访',
      },
    },
    {
      title: '问题',
      dataIndex: 'supportQuestion',
      search: false,
      hideInTable: true,
      align: 'center',
    },
    {
      title: '解决方法',
      dataIndex: 'supportSolution',
      search: false,
      hideInTable: true,
      align: 'center',
    },

    {
      title: '建议',
      dataIndex: 'supportSuggestion',
      search: false,
      hideInTable: true,
      align: 'center',
    },
    {
      title: '备注',
      dataIndex: 'supportComments',
      search: false,
      hideInTable: true,
      align: 'center',
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      hideInTable: false,
      render: (text, record, _, action) => {
        const arrayButton = [];
        if (record.supportStatus === 2 || !operation) {
          arrayButton.push(
            <a
              key="deleteKey"
              onClick={() => {
                setRowData(record);
                actionRef.current.reload();
                setDeleteVisit(true);
              }}
            >
              删除
            </a>,
          );
          // }
          // if (access.aperatorFilter('supportEdit')) {
          arrayButton.push(
            <a
              key="editKey"
              onClick={() => {
                history.push({
                  pathname: `/engineer/onsiteSupportDetail`,
                  query: {
                    id: record.id,
                    // status: record.status,
                  },
                });
              }}
            >
              编辑
            </a>,
          );
        }
        return arrayButton;
      },
    },
  ];

  // const handleSubmit = async () => {
  //     if (formTitle == '新建现场支持') {
  //         const result = await addOnsiteSupport(form.getFieldsValue());
  //         console.log(result, '---add---');
  //         if(result !== null) {
  //             console.log(result, '---');
  //         }
  //     } else {
  //         const result = await updateOnsiteSupport(form.getFieldsValue());
  //         if (result != null) {
  //             message.success('更新成功');
  //         }
  //     }
  //     actionRef.current.reload();
  // }

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="现场支持总览"
        actionRef={actionRef}
        formRef={ref}
        rowKey="id"
        scroll={{ x: 1600 }}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              history.push({
                pathname: `/engineer/onsiteSupportDetail`,
              });
            }}
            type="primary"
          >
            新建现场支持
          </Button>,
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              onsiteSupportExport({
                current: 1,
                pageSize: 5000,
                ...ref.current.getFieldsValue(),
              }).then((res) => {
                const aLink = document.createElement('a');
                document.body.appendChild(aLink);
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(res);
                aLink.setAttribute('download', `现场支持${new Date()}.xlsx`);
                aLink.click();
                document.body.removeChild(aLink);
              });
            }}
            type="primary"
          >
            导出Excel
          </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          console.log(params, sort, filter);
          const sorters = [];
          for (const property in sort) {
            if (sort.hasOwnProperty(property)) {
              if (sort[property] == 'ascend') {
                sorters.push({
                  field: property,
                  desc: false,
                });
              } else {
                sorters.push({
                  field: property,
                  desc: true,
                });
              }
            }
            console.log(property, '---property---');
          }
          console.log(filterValue);
          const result = await getOnsiteSupportByPage({
            ...params,
            ...filterValue,
            sorters: sorters,
          });
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        rowSelection={{}}
      />

      <Modal
        title="删除现场支持"
        visible={deleteVisit}
        onOk={async () => {
          console.log('----删除前的提示---', rowData);
          await delOnsiteSupport({ id: rowData.id });
          actionRef.current.reload();
          setDeleteVisit(false);
        }}
        onCancel={() => {
          setDeleteVisit(false);
        }}
      >
        <p>确定删除现场支持？</p>
      </Modal>
    </PageHeaderWrapper>
  );
};

export default OnsiteSupport;
